package org.redis.cluster.admin.client.factory;

import java.util.concurrent.ConcurrentHashMap;

import org.redis.cluster.config.ClientConfig;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Component
public class RedisClientFactory {
	
	private final ConcurrentHashMap<String, JedisPool> jedisPoolCache=new ConcurrentHashMap<String,JedisPool>();

	/**
	 * 返回客户端
	 * @param config
	 * @return
	 */
	public Jedis getClient(ClientConfig config) {
		JedisPool pool=getJedisPool(config);
		return pool.getResource();
	}
	
	/**
	 * 返回客户端
	 * @param config
	 * @param jedis
	 * @return
	 */
	public boolean returnClient(ClientConfig config,Jedis jedis) {
		jedis.close();
		return true;
	}
	
	protected JedisPool getJedisPool(ClientConfig config) {
		String key=getKey(config);
		JedisPool pool=jedisPoolCache.get(key);
		if(pool!=null) {
			return pool;
		}
		
		jedisPoolCache.putIfAbsent(key, initJedisPool(config));
		return getJedisPool(config);
	}
	
	protected JedisPool initJedisPool(ClientConfig config) {
		JedisPoolConfig poolConfig=new JedisPoolConfig();
		poolConfig.setTestOnBorrow(true);
		poolConfig.setTestOnCreate(true);
		poolConfig.setTestOnReturn(true);
		poolConfig.setTestWhileIdle(true);
		
		return new JedisPool(poolConfig,config.getHost(),config.getPort());
	}
	
	protected String getKey(ClientConfig config) {
		return config.getHost()+"_"+config.getPort();
	}
}